package com.sigmatrix.h5.components;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.sigmatrix.h5.feign.mode.IsvToken;
import com.sigmatrix.h5.properties.SmsProperties;


/**
 * 
 *@ClassName: IsvTokenLoader
 *@Description: 项目启动加载isvToken并放到缓存
 *@author MH
 *@date 2017年12月14日 下午1:46:44
 */
@Component
//@EnableScheduling
public class IsvTokenLoader{
	
	Logger logger = Logger.getLogger(IsvTokenLoader.class);
	
	private static String accessCode;
	
	private static final String ACCESS_CODE_KEY = "accessCode";
	
	public static final String SMS_CODE_PEFFIX = "smscodeprefixx";
	
	@Autowired
	private FeignManager feignManager;
	
	@Autowired	
	private RedisClient redisClient;
	
	@Autowired
	private SmsProperties smsProperties;
	
//	@Override
//	public void run(String... args) throws Exception {
////		accessCode = redisClient.get(ACCESS_CODE_KEY);
////		if(StringUtils.isBlank(accessCode)){
////			IsvToken isvToken = feignManager.isvToken(smsProperties.getUserName(),smsProperties.getUserPassword());
////			accessCode = isvToken.getAccessToken();
////			redisClient.set(ACCESS_CODE_KEY, accessCode,110,TimeUnit.MINUTES);
////		}
//		
//	}
	
	public String getIsvToken(){
		return redisClient.get(ACCESS_CODE_KEY);
	}
	
//	@Scheduled(cron="0 1/110 * * * ?")
	public void refreshIsvToken(){
		String temp = redisClient.get(ACCESS_CODE_KEY);
		if(StringUtils.isBlank(temp)){
			String token = feignManager.refreshIsvToken(accessCode).getAccessToken();
			accessCode = token;
			redisClient.set(ACCESS_CODE_KEY, accessCode,110,TimeUnit.MINUTES);
		}
	}
}
